package com.gitee.blogcase.simplerabbitmqcase.consumer;

import com.gitee.blogcase.simplerabbitmqcase.producer.MessagesCallbackProducer;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * RabbitMQ Message 回调地址消费者测试
 * @author wuwentao
 */
@Component
@Slf4j
public class MessagesCallbackConsumer {
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MessagesCallbackProducer.MESSAGE_CALLBACK_EXCHANGE, durable = "true", type = ExchangeTypes.DIRECT),
            value = @Queue(value = MessagesCallbackProducer.MESSAGE_CALLBACK_QUEUE, durable = "true"),
            key = MessagesCallbackProducer.MESSAGE_CALLBACK_ROUTINGKEY
    ))
    @RabbitHandler
    public void consumer(String content, Channel channel, Message message) throws IOException {
        if("成功".equals(content)){
            log.info("消息处理成功:{}",content);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); // 手动确认消息消费成功
        }else{
            if(message.getMessageProperties().getRedelivered()){
                log.info("消息已被处理过了请勿重复处理消息:{}",content);
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false); // 拒绝该消息，消息会被丢弃，不会重回队列
            }else{
                log.info("消息处理失败等待重新处理:{}",content);
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }
}
